/**
 * PDFUtilities.java
 * Nov 19, 2013
 * Copyright: phongtdse60732@fpt.edu.vn
 */
package XMLUtilities;

/**
 * @author Lubu
 * @version 1.0
 */
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;

import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.sax.SAXResult;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.apache.fop.apps.FOPException;
import org.apache.fop.apps.FOUserAgent;
import org.apache.fop.apps.Fop;
import org.apache.fop.apps.FopFactory;
import org.apache.fop.apps.MimeConstants;

public class PDFUtilities {
	public static byte[] printPDF(String xmlStream, String xslPath,
			String foPath, String pathFile) {
		try {
			// tranform xml to fo
			TransformerFactory tf = TransformerFactory.newInstance();
			StreamSource xsltFile = new StreamSource(xslPath);
			Transformer trans = tf.newTransformer(xsltFile);
			trans.setParameter("pathFile", pathFile);

			System.out.println(xmlStream);
			InputStream is = new ByteArrayInputStream(xmlStream.getBytes());
			StreamSource xmlFile = new StreamSource(is);
			// StreamSource xmlFile = new StreamSource(xmlStream);
			StreamResult foFile = new StreamResult(new FileOutputStream(foPath));
			trans.transform(xmlFile, foFile);

			// create pdf from fo
			FopFactory ff = FopFactory.newInstance();
			FOUserAgent fua = ff.newFOUserAgent();
			ByteArrayOutputStream ous = new ByteArrayOutputStream();
			Fop fop = ff.newFop(MimeConstants.MIME_PDF, fua, ous);

			trans = tf.newTransformer();
			File fo = new File(foPath);
			Source src = new StreamSource(fo);
			Result result = new SAXResult(fop.getDefaultHandler());
			trans.transform(src, result);
			return ous.toByteArray();
		} catch (TransformerException ex) {
			ex.printStackTrace();
		} catch (FOPException ex) {
			ex.printStackTrace();
		} catch (FileNotFoundException ex) {
			ex.printStackTrace();
		}
		return null;
	}
}
